package com.gzhryc.jdbc;

import java.sql.Connection;

import org.h2.jdbcx.JdbcConnectionPool;
import org.h2.tools.Server;

import com.gzhryc.jdbc.enums.DbType;
import com.gzhryc.jdbc.models.ConnectInfo;

public class H2DatabaseService {

	String dbName;
	Integer port;
	String userName = "root";
	String userPwd = "";

	JdbcConnectionPool pool;
	Server tcpServer;
	Server webServer;

	public H2DatabaseService(String dbName, Integer port) {
		this.dbName = dbName;
		this.port = port;
	}

	public H2DatabaseService(String dbName, Integer port, String userName, String userPwd) {
		this.dbName = dbName;
		this.port = port;
		this.userName = userName;
		this.userPwd = userPwd;
	}

	public boolean run() {
		try {
			tcpServer = Server.createTcpServer(new String[] { "-tcpPort", port.toString() });
			tcpServer.start();
			/*
			 * webServer = Server.createWebServer(new
			 * String[]{"-webPort",webPort.toString()}); webServer.start();
			 */
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public Connection getConn() {
		try {
			if (pool == null) {
				Class.forName("org.h2.Driver");
				pool = JdbcConnectionPool.create(getUrl(), userName, userPwd);
				pool.setMaxConnections(30);
			}
			return pool.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public Connection getMemoryConn() {
		try {
			if (pool == null) {
				Class.forName("org.h2.Driver");
				pool = JdbcConnectionPool.create(getMemoryUrl(), userName, userPwd);
				pool.setMaxConnections(30);
			}
			return pool.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public void close() {
		if (tcpServer != null) {
			tcpServer.stop();
		}
		if (webServer != null) {
			webServer.stop();
		}
	}

	public String getUrl() {
		return "jdbc:h2:tcp://127.0.0.1:" + tcpServer.getPort() + "/~/" + dbName;
	}

	public String getMemoryUrl() {
		return "jdbc:h2:tcp://127.0.0.1:" + tcpServer.getPort() + "/mem:" + dbName + ";DB_CLOSE_DELAY=-1";
	}

	public ConnectInfo getInfo() {
		ConnectInfo result = new ConnectInfo(DbType.h2);
		result.setDbName(dbName);
		result.setDriverClassName("org.h2.Driver");
		result.setIp("127.0.0.1");
		result.setPort(port);
		result.setUrl(getUrl());
		result.setUserName(userName);
		result.setPassword(userPwd);
		return result;
	}
	
	public ConnectInfo getMemoryInfo() {
		ConnectInfo result = new ConnectInfo(DbType.h2);
		result.setDbName(dbName);
		result.setDriverClassName("org.h2.Driver");
		result.setIp("127.0.0.1");
		result.setPort(port);
		result.setUrl(getMemoryUrl());
		result.setUserName(userName);
		result.setPassword(userPwd);
		return result;
	}
}
